<?php
/**
 * Created by PhpStorm.
 * User: 李大爷
 * Date: 2019/3/1
 * Time: 15:44
 */

namespace app\controllers;

use app\models\Permission;
use app\models\Role;
use Yii;
use yii\helpers\Url;
use yii\helpers\VarDumper;

class RoleController extends BaseController
{
    /**
     * 角色管理列表
     * @return string|\yii\web\Response
     */
    public function actionIndex()
    {
        if (Yii::$app->request->isAjax){
            $query = Role::find()->where(['type'=>1])->orderBy('created_at desc');
            $count = $query->count();

            $page = Yii::$app->request->get('page',1);
            $limit = Yii::$app->request->get('limit',10);
            $data = $query->offset(($page-1)*$limit)->limit($limit)->asArray()->all();
            foreach ($data as &$d){
                $d['edit_url'] = Url::to(['edit','name'=>$d['name']]);
                $d['destroy_url'] = Url::to(['destroy','name'=>$d['name']]);
                $d['role_url'] = Url::to(['role','name'=>$d['name']]);
                $d['permission_url'] = Url::to(['permission','name'=>$d['name']]);
                $childRole = Yii::$app->authManager->getChildRoles($d['name']);
                //移除自身
                unset($childRole[$d['name']]);
                $d['roles'] = $childRole;
            }
            return $this->asJson([
                'code' => 0,
                'msg' => '请求成功',
                'count' => $count,
                'data' => $data
            ]);
        }
        return $this->render('index');
    }

    /**
     * 添加角色
     * @return string|\yii\web\Response
     */
    public function actionCreate()
    {
        $model = new Role();
        if (Yii::$app->request->isPost){
            $data = Yii::$app->request->post();
            $model->scenario = 'create';
            if ($model->load($data,'')&&$model->createRole()){
                Yii::$app->session->setFlash('info','添加成功');
                return $this->redirect(['index']);
            }
        }
        return $this->render('create',['model'=>$model]);
    }

    /**
     * 编辑角色
     * @param $name
     * @return string|\yii\web\Response
     */
    public function actionEdit($name)
    {
        $model = Role::findOne(['name'=>$name,'type'=>1]);
        if ($model==null){
            throw new NotFoundHttpException('角色不存在');
        }
        if (Yii::$app->request->isPost){
            $data = Yii::$app->request->post();
            $model->scenario = 'edit';
            if ($model->load($data,'')&&$model->editRole()){
                Yii::$app->session->setFlash('info','更新成功');
                return $this->redirect(['index']);
            }
        }

        return $this->render('edit',['model'=>$model]);
    }

    /**
     * 删除角色
     * @param $name
     * @return \yii\web\Response
     */
    public function actionDestroy($name)
    {
        $auth = Yii::$app->authManager;
        $role = $auth->getRole($name);
        if ($role === null){
            return $this->asJson(['code'=>1,'msg'=>'角色不存在']);
        }
        if ($auth->remove($role)){
            return $this->asJson(['code'=>0,'msg'=>'删除成功']);
        }
        return $this->asJson(['code'=>1,'msg'=>'删除失败']);
    }

    /**
     * 分配子角色
     * @param $name
     * @return string|\yii\web\Response
     */
    public function actionRole($name)
    {
        $auth = Yii::$app->authManager;
        $role = $auth->getRole($name);
        if ($role==null){
            throw new NotFoundHttpException('角色不存在');
        }

        if (Yii::$app->request->isPost){
            $roleNames = Yii::$app->request->post('role',[]);

            $trans = Yii::$app->db->beginTransaction();
            try{
                //移除角色的所有子角色
                $hasRole = $auth->getChildRoles($name);
                foreach ($hasRole as $role_child){
                    $auth->removeChild($role,$role_child);
                }
                //重新添加角色
                foreach ($roleNames as $name){
                    $child = $auth->getRole($name);
                    $auth->addChild($role,$child);
                }

                $trans->commit();
                Yii::$app->session->setFlash('info','更新成功');
                return $this->render('index');
            }catch (\Exception $exception){
                $trans->rollBack();
                Yii::$app->session->setFlash('info','更新失败');
                return $this->refresh();
            }
        }

        //所有角色
        $roles = $auth->getRoles();
        foreach ($roles as $key=>$item){
            if (!$auth->canAddChild($role,$item)){
                unset($roles[$key]);
            }
        }
        //角色已拥有的子角色
        $ownRoles = $auth->getChildRoles($name);

        return $this->render('role',['model'=>$role,'roles'=>$roles,'ownRoles'=>$ownRoles]);
    }

    /**
     * 分配权限
     * @param $name
     * @return string|\yii\web\Response
     * @throws \yii\base\Exception
     */
    public function actionPermission($name)
    {
        $auth = Yii::$app->authManager;
        $role = $auth->getRole($name);
        if ($role==null){
            throw new NotFoundHttpException('角色不存在');
        }

        //所有权限
        $permission = Permission::tree();
        //角色已拥有的权限
        $ownPermission = $auth->getPermissionsByRole($name);

        if (Yii::$app->request->isPost){
            $data = Yii::$app->request->post('permission',[]);
            //移除已有的权限
            foreach ($ownPermission as $o){
                $auth->removeChild($role,$o);
            }
            //添加新的权限
            foreach ($data as $d){
                $newPermission = $auth->getPermission($d);
                if ($auth->canAddChild($role,$newPermission)){
                    $auth->addChild($role,$newPermission);
                }
            }
            Yii::$app->session->setFlash('info','权限分配成功');
            return $this->redirect(['index']);
        }
        return $this->render('permission',['model'=>$role,'permission'=>$permission,'ownPermission'=>$ownPermission]);

    }
    
}